﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataAccess
{
	public class ControllerData<K,D> : IControllerData<K,D>
	{
		// ATTRIBUT		

		// Moteur de la BDD sérialisation binaire
		private BinarySerialization<Dictionary<K, D>> _oBS;

		// Flag indiquant si dico a été modifié
		private bool _bDataAltered;
		public bool DataAltered
		{
			get { return _bDataAltered; }
		}

		// Dictionnaire Key/Data
		private Dictionary<K, D> _oDicoData;
		public Dictionary<K, D> DicoData
		{
			// METHODE DQL
			get 
			{ 			
				if( _bDataAltered )
				{
					ReadTable();
				}
				return _oDicoData;
			}
		}

		// Nom de la table de la BDD
		private readonly string _strNomTable;		

		//CONSTRUCTEUR
		public ControllerData(string strNomtable)
		{
			// Nom de la table = nom de la classe D
			_strNomTable	= strNomtable;

			// Création moteur BDD
			string strNomFichier = _strNomTable+".bin";
			_oBS			= new BinarySerialization<Dictionary<K, D>>( strNomFichier );

			// Indication dico modifié
			_bDataAltered	= true;

			// Création dico Key/Data
			_oDicoData		= new Dictionary<K,D>();
			
		}

		public void Dispose()
		{
			if( _oDicoData != null )
				SaveTable();
		}

		// METHODE
		private void SaveTable()
		{
			if( _oDicoData != null )
			{
				_oBS.Save(_oDicoData);
				_bDataAltered = true;
			}
		}

		private void ReadTable()
		{
			if( _oDicoData != null )
			{
				_oDicoData = _oBS.Load();
				_bDataAltered = false;
			}
		}		

		// METHODE DML
		public void InsertData(K oKey, D oDataNew)
		{
			if( _oDicoData != null && !_oDicoData.ContainsKey( oKey ) )
			{					
				_oDicoData.Add( oKey, oDataNew );
				SaveTable();
			}
		}

		public void UpdateData(K oKey, D oData)
		{
			D oDataBase;
			if( _oDicoData != null && _oDicoData.ContainsKey( oKey )
				&& _oDicoData.TryGetValue(oKey, out oDataBase) && oDataBase != null )
			{				
				_oDicoData[oKey] = (D)oData;
				SaveTable();
			}
		}

		public void DeleteData(K Key)
		{
			if( _oDicoData != null && _oDicoData.ContainsKey( Key ) )
			{
				_oDicoData.Remove( Key );
				SaveTable();
			}
		}

		// METHODE DDL

		public void CreateTable()
		{
			_oBS.CreateFile();
			_bDataAltered = true;
		}

		public void AlterTable()
		{
			throw new NotImplementedException();
			//_bDicoAltered = true;
		}

		public void DropTable()
		{
			_oBS.DeleteFile();
			_bDataAltered = true;
		}
	}
}
